package com.kingwang.demo.springsecuritytokendemo.config;

import com.kingwang.demo.springsecuritytokendemo.security.InMemoryTokenSessionManager;
import com.kingwang.demo.springsecuritytokendemo.security.InMemoryTokenUserDetailsService;
import com.kingwang.demo.springsecuritytokendemo.security.JsonResponseAuthenticationFailureHandler;
import com.kingwang.demo.springsecuritytokendemo.security.TokenBasedAuthenticationFilter;
import com.kingwang.demo.springsecuritytokendemo.security.TokenBasedAuthenticationProvider;
import com.kingwang.demo.springsecuritytokendemo.security.TokenLogoutHandler;
import com.kingwang.demo.springsecuritytokendemo.security.TokenSessionManager;
import com.kingwang.demo.springsecuritytokendemo.security.TokenUserDetailsService;
import com.kingwang.demo.springsecuritytokendemo.utils.CurrentDateTimeGenerator;
import com.kingwang.demo.springsecuritytokendemo.utils.DateTimeGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.AnonymousAuthenticationFilter;
import org.springframework.security.web.authentication.logout.HttpStatusReturningLogoutSuccessHandler;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.security.web.util.matcher.OrRequestMatcher;
import org.springframework.security.web.util.matcher.RequestMatcher;

/**
 * @author King
 */
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    private static final String URL_TOKEN = "/token";
    private static final String URL_LOGIN = "/login";
    private static final String URL_LOGOUT = "/logout";
    private static final String URL_PROTECTED = "/api/**";

    private TokenUserDetailsService tokenUserDetailsService;
    private UserDetailsService userDetailsService;
    private SessionConfig sessionConfig;

    @Autowired
    public SecurityConfig(SessionConfig sessionConfig) {
        super();

        this.sessionConfig = sessionConfig;

        InMemoryTokenUserDetailsService inMemoryUserDetailsService = new InMemoryTokenUserDetailsService();

        this.tokenUserDetailsService = inMemoryUserDetailsService;
        this.userDetailsService = inMemoryUserDetailsService;
    }

    /**
     * Spring Security配置
     *
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors()
                .and()
                .csrf()
                .disable()
//                .sessionManagement()
//                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
//                .and()
                .httpBasic()
                .disable()
                // TokenBasedAuthenticationFilter放在最后一个Filter的位置上
                // 仅优先于匿名访问的Filter
                .addFilterBefore(tokenBasedAuthenticationFilter(), AnonymousAuthenticationFilter.class)
                .authorizeRequests()
                .antMatchers(
                        URL_TOKEN,
                        URL_LOGIN
                ).permitAll()
                .anyRequest()
                .authenticated()
                .and()
                .formLogin()
                .and()
                .logout()
                // 设置LogoutHandler
                .addLogoutHandler(new TokenLogoutHandler(sessionManager()))
                // 设置LogoutSuccessHandler
                .logoutSuccessHandler(new HttpStatusReturningLogoutSuccessHandler());
    }

    /**
     * 设置UserDetailsService和AuthenticationProvider
     *
     * @param auth
     * @throws Exception
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(this.userDetailsService);
        auth.inMemoryAuthentication()
                .withUser("user")
                .password(passwordEncoder().encode("123456"))
                .authorities("ROLE_user")
                .and()
                .passwordEncoder(passwordEncoder());
        auth.authenticationProvider(
                new TokenBasedAuthenticationProvider(this.userDetailsService, sessionManager()));
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    /**
     * 自定义TokenBasedAuthenticationFilter
     *
     * @return
     * @throws Exception
     */
    @Bean
    public TokenBasedAuthenticationFilter tokenBasedAuthenticationFilter() throws Exception {
        RequestMatcher requestMatcher = new OrRequestMatcher(
                new AntPathRequestMatcher(URL_PROTECTED),
                new AntPathRequestMatcher(URL_LOGOUT)
        );

        TokenBasedAuthenticationFilter result = new TokenBasedAuthenticationFilter(requestMatcher);

        result.setAuthenticationManager(authenticationManager());
        result.setAuthenticationFailureHandler(jsonResponseAuthenticationFailureHandler());

        return result;
    }

    /**
     * 自定义AuthenticationFailureHandler
     *
     * @return
     */
    @Bean
    public JsonResponseAuthenticationFailureHandler jsonResponseAuthenticationFailureHandler() {
        return new JsonResponseAuthenticationFailureHandler();
    }

    /**
     * 自定义UserDetailsService
     *
     * @return
     */
    @Override
    @Bean
    public UserDetailsService userDetailsService() {
        return this.userDetailsService;
    }

    /**
     * 自定义TokenUserDetailsService Bean注入
     *
     * @return
     */
    @Bean
    public TokenUserDetailsService tokenUserDetailsService() {
        return this.tokenUserDetailsService;
    }

    /**
     * 自定义TokenSessionManager Bean注入
     *
     * @return
     */
    @Bean
    public TokenSessionManager sessionManager() {
        return new InMemoryTokenSessionManager(this.sessionConfig, dateTimeGenerator());
    }

    /**
     * 自定义日期时间注入
     *
     * @return
     */
    @Bean
    public DateTimeGenerator dateTimeGenerator() {
        return new CurrentDateTimeGenerator();
    }
}
